<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRoute } from 'vue-router'
import { timeFormat_2, copyToCliboard, toYuan, timeStamp } from '@/hooks/util'
import { message } from 'ant-design-vue'
import * as promotionCenterApi from '@/api/promotionCenter'

interface Pagination {
  page: number
  pageSize: number
  total: number
  current?: number
  onChange: Function
  showSizeChanger: boolean
  showQuickJumper: boolean
}

const handlePageChange = (page: any, pageSize: any) => {
  pagination.value.pageSize = pageSize
  searchParams.value.pageSize = pageSize
}

const pagination = ref<Pagination>({
  page: 1,
  pageSize: 10,
  total: 0,
  onChange: handlePageChange,
  showSizeChanger: true,
  showQuickJumper: true
})
let loading = ref<boolean>(false)

interface SearchParams {
  currentPage: number
  pageSize: number
  [propName: string]: any
}
const searchParams = ref<SearchParams>({
  currentPage: pagination.value.page,
  pageSize: pagination.value.pageSize,
})

const dataSource = ref([])
const columns = [
  {
    title: '卡密',
    key: 'card',
    width: 300,
  },
  {
    title: '商品标题',
    key: 'productTitle',
    width: 100,
  },
  {
    title: '商品积分',
    key: 'productPrice',
    width: 100,
  },
  {
    title: '兑换状态',
    key: 'status',
    width: 100,
  },
  {
    title: '创建时间',
    key: 'createTime',
    width: 180,
  },
]

// 翻页
const changePage = (e: any) => {
  pagination.value.current = e.current
  pagination.value.pageSize = e.pageSize
  searchParams.value.currentPage = pagination.value.current as number
  getList()
}

// ---------------------------------------------------------

const getList = async () => {
  loading.value = true
  try {
    let {
      state,
      data,
      message: msg,
    } = await promotionCenterApi.getExchangePointProductRecordList(searchParams.value)
    if (state === 200) {
      dataSource.value = data.list
      pagination.value.total = Number(data.totalCount)
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
  loading.value = false
}

onMounted(() => {
  getList()
})

defineExpose({
  getList,
})

// 查询
const formRef = ref()
interface FormState {
  time?: [any, any]
  status: number
}
const formState = reactive<FormState>({})

// 时间选择器
import locale from 'ant-design-vue/es/date-picker/locale/zh_CN'
import 'dayjs/locale/zh-cn'
import type { Dayjs } from 'dayjs'
type RangeValue = [Dayjs, Dayjs] | [string, string] | undefined
let startTime = ref<string>()
let endTime = ref<string>()
const changeTime = (e: RangeValue | [string, string], dataString: [string, string]) => {
  console.log(dataString)
  startTime.value = dataString[0]
  endTime.value = dataString[1]
}
// 将选择范围控制在7天
import type { Moment } from 'moment'
const dates = ref<Moment[]>([])
const disabledDate = (current: Moment) => {
  if (!dates.value || dates.value.length === 0) {
    return false
  }
  const diffDate = current.diff(dates.value[0], 'days')
  return Math.abs(diffDate) > 6
}
const onCalendarChange = (val: Moment[]) => {
  dates.value = val
}

// 兑换状态
import type { SelectProps } from 'ant-design-vue'
const statusList = ref<SelectProps['options']>([
  {
    label: '兑换成功',
    value: 1,
  },
  {
    label: '兑换失败',
    value: 2,
  },
])

const search = () => {
  pagination.value.current = 1
  searchParams.value.currentPage = 1
  formRef.value.validate().then(() => {
    if(startTime.value && endTime.value){
      searchParams.value.beginTime = timeStamp(`${startTime.value} 00:00:00`)
      searchParams.value.endTime = timeStamp(`${endTime.value} 23:59:59`)
    }
    if(formState.status){
      searchParams.value.status = formState.status
    }
    getList()
  })
}

const reset = () => {
  pagination.value.current = 1
  searchParams.value.currentPage = 1
  formRef.value.resetFields()
  startTime.value = ''
  endTime.value = ''
  for (let key in searchParams.value) {
    if (key != 'currentPage' && key != 'pageSize')
      searchParams.value.hasOwnProperty(key) && delete searchParams.value[key]
  }

  getList()
}
</script>

<template>
  <div class="searchBox">
    <a-form ref="formRef" layout="inline" :model="formState" class="formClass">
      <a-form-item label="时间" name="time">
        <a-range-picker
          v-model:value="formState.time"
          :disabledDate="disabledDate"
          @calendarChange="onCalendarChange"
          :locale="locale"
          :placeholder="['开始日期', '结束日期']"
          @change="changeTime"
          style="height: 32px; line-height: 32px"
        />
      </a-form-item>

      <a-form-item label="兑换状态" name="status">
        <a-select
          v-model:value="formState.status"
          placeholder="兑换状态"
          style="width: 150px"
          allowClear
        >
          <a-select-option v-for="(item, index) in statusList" :key="index" :value="item.value">
            {{ item.label }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item>
        <a-button type="primary" @click="search">搜索</a-button>
        <a-button @click="reset">重置</a-button>
      </a-form-item>
    </a-form>
  </div>

  <a-table
    style="overflow-x: scroll"
    :columns="columns"
    :data-source="dataSource"
    :pagination="pagination"
    :loading="loading"
    @change="changePage"
    rowKey="id"
    :scroll="{ x: 1000 }"
  >
    <!-- :row-selection="{ selectedRowKeys: selectedRowKey, onChange: onSelectChange }" -->
    <template #emptyText>
      <a-empty description="暂无数据" />
    </template>

    <template #headerCell="{ column }">
      <template v-if="column.key === 'id'">
        <span>卡密</span>
      </template>
    </template>

    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'card'">
        <div>
          {{ record.card || '无' }}
          <a v-if="record.card != ''" @click="copyToCliboard(record.card)"><CopyOutlined /></a>
        </div>
      </template>

      <template v-else-if="column.key === 'productTitle'">
        <div>{{ record.productTitle }}</div>
      </template>

      <template v-else-if="column.key === 'productPrice'">
        <div>{{ record.productPrice }}</div>
      </template>

      <template v-else-if="column.key === 'status'">
        <a-tag color="blue" v-if="record.status == 1">兑换成功</a-tag>
        <a-tag color="red" v-if="record.status == 2">兑换失败</a-tag>
        <a-tooltip placement="topLeft" :title="record.failReason" v-if="record.status == 2">
          <a><question-circle-outlined style="color: red" /></a>
        </a-tooltip>
      </template>

      <template v-else-if="column.key === 'createTime'">
        <div>{{ timeFormat_2(record.createTime) }}</div>
      </template>
    </template>
  </a-table>
</template>

<style lang="less" scoped>
.hiddenText {
  display: inline-block;
  max-width: 140px;
  overflow: hidden;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  line-height: 16px;
}

.searchBox {
  margin-bottom: 10px;
  display: flex;

  input {
    width: 200px;
    margin-right: 10px;
  }

  button {
    margin-right: 10px;
  }
}
</style>
